import { cloneDeep } from 'lodash'
import { defineComponent } from 'vue'

export default defineComponent({
  props: {
    // 表单展示控制
    // 通过.sync + $emit('update:show') 同步状态到父组件
    show: Boolean,
    // 表单 v-model
    modelValue: [Object, Array],
    // 表单模式 eg. 'create' | 'update'
    mode: {
      type: String,
      default: 'create'
    },
    // 内联表单 - 不由 dialog 承载的表单
    inline: Boolean
  },
  data () {
    return {
      innerDialogShow: this.show,
      formData: this.modelValue || this.defaultFormData
    }
  },
  computed: {
    widgetData () {
      return this.data && this.data.data ? this.data.data : {}
    }
  },
  watch: {
    innerDialogShow () {
      this.$emit('update:show', this.innerDialogShow)
    },
    show () {
      this.innerDialogShow = this.show
    },
    modelValue (modelValue) {
      this.formData = modelValue
    },
    formData () {
      this.$emit('update:modelValue', this.formData)
    }
  },
  methods: {
    submit () {
      this.$emit('update:modelValue', this.formData)
      this.$emit('submit', this.formData)
      this.innerDialogShow = false
    },
    async createWidget (option) {
      const widget = {
        // 组件基础数据
        ...option,
        // 组件编辑数据
        ...cloneDeep(this.formData)
      }
      await this.$store.dispatch('widget/createWidget', widget)
      this.innerDialogShow = false
      this.$emit('submitted', widget)
    },
    async saveWidget () {
      // 删除布局数据 - 不允许组件直接更新布局信息
      delete this.formData.x
      delete this.formData.y
      delete this.formData.w
      delete this.formData.h
      console.log(JSON.stringify({
        ...this.data,
        ...cloneDeep(this.formData)
      }))
      await this.$store.dispatch('widget/updateWidget', {
        ...this.data,
        ...cloneDeep(this.formData)
      })
      this.innerDialogShow = false
      this.$emit('submitted', this.formData)
    }
  }
})
